package com.zaoqi.consumer.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Random;

public class CustomRandomLoadBalancerClient implements ReactorServiceInstanceLoadBalancer {

    private final ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;
    private final Random random = new Random();

    public CustomRandomLoadBalancerClient(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider) {
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
    }

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider.getIfAvailable();
        if (supplier == null) {
            return Mono.just(new EmptyResponse());
        }

        // 创建一个 cached Mono，并复用
        Mono<List<ServiceInstance>> instanceListMono = supplier.get().next().cache(); // ✅ 缓存服务列表

        // 生成随机数只在第一次订阅时执行
        return instanceListMono.map(this::getInstanceResponse).cache(); // ✅ 缓存选择结果
    }


    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) {
        if (instances.isEmpty()) {
            return new EmptyResponse();
        }
        // 生成 0 到 99 的随机数
        int randomNumber = random.nextInt(100);
        System.out.println("生成的随机数: " + randomNumber);
        // 根据奇偶性选择实例：偶数选择第一个，奇数选择第二个（如果不存在则选第一个）
        int index = (randomNumber % 2 == 0) ? 0 : 1;
        if (index >= instances.size()) {
            index = 0;
        }
        ServiceInstance chosen = instances.get(index);
        System.out.println("选中实例: " + chosen.getUri());
        return new DefaultResponse(chosen);
    }
}
